﻿using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Security.AccessControl;


namespace TTprotons.Crm.ExternalView.SetupCustomActions
{
    [RunInstaller(true)]
    public partial class ConfigurePermission : System.Configuration.Install.Installer
    {
        public ConfigurePermission()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            var targetDir = Context.Parameters["InstallDirectory"];

            try
            {
                AddDirectorySecurity(targetDir, Environment.MachineName + @"\ASPNET", FileSystemRights.Modify, AccessControlType.Allow);
                AddDirectorySecurity(targetDir, Environment.MachineName + @"\ASPNET", FileSystemRights.Write, AccessControlType.Allow);
            }
            catch (Exception)
            { }

            try
            {
                AddDirectorySecurity(targetDir, @"NT AUTHORITY\NETWORK SERVICE", FileSystemRights.Modify, AccessControlType.Allow);
                AddDirectorySecurity(targetDir, @"NT AUTHORITY\NETWORK SERVICE", FileSystemRights.Write, AccessControlType.Allow);
            }
            catch (Exception)
            { }

            try
            {
                AddDirectorySecurity(targetDir, @"IIS AppPool\DefaultAppPool", FileSystemRights.Modify, AccessControlType.Allow);
                AddDirectorySecurity(targetDir, @"IIS AppPool\DefaultAppPool", FileSystemRights.Write, AccessControlType.Allow);
            }
            catch (Exception)
            { }
        }

        /// <summary>        
        /// Adds an ACL entry on the specified directory for the specified account.        
        /// </summary>        
        /// <param name="dirName">Folder path to add the permissions to</param>        
        /// <param name="Account"></param>        
        /// <param name="Rights"></param>        
        /// <param name="ControlType"></param>        
        private static void AddDirectorySecurity(string folderName, string account, FileSystemRights rights, AccessControlType controlType)
        {
            // Create a new DirectoryInfo object.            
            DirectoryInfo dInfo = new DirectoryInfo(folderName);

            // Get a DirectorySecurity object that represents the current security settings.            
            DirectorySecurity dSecurity = dInfo.GetAccessControl();

            // Add the FileSystemAccessRule to the security settings.             
            dSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, controlType));

            // Set the new access settings.            
            dInfo.SetAccessControl(dSecurity);
        }
    }
}